#include "smartbox.h"
#include "common/http_tool.h"

using namespace app;

int main(int argc, char **argv)
{
  int ret = 0;
  if (!bf::exists(CFG_PATH)) { std::cout << "\"" << CFG_PATH << "\"is not exists..." << std::endl; return ret; }
  if (argc == 2 && std::string(argv[1]) == "--version"){
    std::cout << "smartbox version: " << CUR_VERSION << std::endl;
    return 0;
  }
  int mode = 1;
  if (argc == 2) { mode = std::stoi(argv[1]);}

  // // 注册码 x86
  // /* CPU ID sudo dmidecode -t 4 | grep ID
  // 主板序列号 sudo dmidecode -t 2 | grep Serial
  // MAC地址 sudo lshw -c network | grep serial | head -n 1 */


  // 读取本地配置
  ConfigInfo cfg_ifo;
  if ((ret = string_to_struct(CFG_PATH, cfg_ifo, true)) != 0) { 
    std::cout << "'string_to_struct' error: " <<  ret << std::endl; return ret; 
  }
  LogInfo* log_ifo = new LogInfo(mode, cfg_ifo.historyDir, "log"); 
  
  if (mode != 0) {
    // 启动时就开始删除文件
    remove_file(cfg_ifo.historyDir, 1* 60* 60, ".jpg");
    remove_file(cfg_ifo.historyDir, cfg_ifo.historyDay * 24* 60* 60, "");
    
    // 执行附加任务
    for (auto& t : cfg_ifo.tasks) {
      std::this_thread::sleep_for(std::chrono::seconds(5));
      system(t.c_str()); 
    }
    std::this_thread::sleep_for(std::chrono::seconds(10));
    common::api_addDeleteStrategy(cfg_ifo.mediaKitInfo, log_ifo);
  }

  // 初始化模型
  SmartBox *smartbox = new SmartBox(&cfg_ifo, log_ifo);
  spdlog::get("logger")->info("smartbox init model ok: {}", ret);

  // 启动线程开始分析
  // 0 则为本地调试模式
  if (mode != 0) {
    // if ((ret = act_code->check_expiration(check_cpu_adress)) != 0) { 
    //   spdlog::get("logger")->info("smartbox unknow error: {}", ret); return ret;
    //   return ret;
    // }
    std::thread t2(&SmartBox::run, smartbox);
    t2.detach();
  }


  // 启动http服务端
  Server svr;
  svr.Get("/hi", [](const Request& req, Response& res) {
    res.set_content("c++ service for xc smartbox start ok!", "text/plain");
  });
  svr.Post("/api/version", [](const Request& req, Response& res) {
    std::cout << "\n\nin /api/version" << std::endl;
    std::string return_msg;
    Json::Value root;
    root["code"] = 0;
    root["msg"] = "ok";
    root["version"] = CUR_VERSION;
    return_msg = root.toStyledString();
    res.set_content(return_msg, "application/json");
  });
  svr.Get("/api/heart", [&](const auto& req, auto& res){
    std::cout << "\n\nin /api/heart" << std::endl;
    std::string return_msg;
    return_error(0, "ok", return_msg);
    res.set_content(return_msg, "application/json");
  });
  svr.Get("/api/stop", [&](const auto& req, auto& res){
    std::cout << "\n\nin /api/stop" << std::endl;
    res.set_content("", "application/text");
    exit(0);
  });

  // 监听端口
  spdlog::get("logger")->info("c++ service for xc smartbox start ok!");
  svr.listen("0.0.0.0", 9999);
  return 0;
}


